package com.kaizeli.website.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaizeli.website.mapper.PaymentMapper;
import com.kaizeli.website.pojo.entity.Payment;
import com.kaizeli.website.pojo.dto.PaymentDTO;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 回款服务实现类
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public Result<List<PaymentDTO>> getPaymentsByProjectId(Long projectId) {
        try {
            List<PaymentDTO> payments = paymentMapper.selectByProjectId(projectId);
            return Result.success(payments);
        } catch (Exception e) {
            return Result.error(500, "查询回款记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PaymentDTO>> getPaymentsByPaymentStatus(String paymentStatus) {
        try {
            List<PaymentDTO> payments = paymentMapper.selectByPaymentStatus(paymentStatus);
            return Result.success(payments);
        } catch (Exception e) {
            return Result.error(500, "查询回款记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Payment> createPayment(Payment payment) {
        try {
            // 设置默认值
            if (payment.getPaymentStatus() == null) {
                payment.setPaymentStatus("已到账");
            }
            if (payment.getIsPartialPayment() == null) {
                payment.setIsPartialPayment(0);
            }
            if (payment.getRemainingAmount() == null) {
                payment.setRemainingAmount(BigDecimal.ZERO);
            }
            
            payment.setCreateTime(LocalDateTime.now());
            payment.setUpdateTime(LocalDateTime.now());
            save(payment);
            return Result.success(payment);
        } catch (Exception e) {
            return Result.error(500, "创建回款记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Payment> updatePayment(Payment payment) {
        try {
            payment.setUpdateTime(LocalDateTime.now());
            updateById(payment);
            return Result.success(payment);
        } catch (Exception e) {
            return Result.error(500, "更新回款记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updatePaymentStatus(Long id, String paymentStatus) {
        try {
            Payment payment = getById(id);
            if (payment == null) {
                return Result.error(404, "回款记录不存在");
            }
            
            int result = paymentMapper.updatePaymentStatus(id, paymentStatus);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error(500, "更新回款状态失败");
            }
        } catch (Exception e) {
            return Result.error(500, "更新回款状态失败：" + e.getMessage());
        }
    }

    @Override
    public Result<BigDecimal> calculateTotalPayment(Long projectId) {
        try {
            BigDecimal totalPayment = paymentMapper.calculateTotalPayment(projectId);
            return Result.success(totalPayment);
        } catch (Exception e) {
            return Result.error(500, "计算总回款金额失败：" + e.getMessage());
        }
    }

    @Override
    public Result<BigDecimal> calculateRemainingAmount(Long projectId) {
        try {
            BigDecimal remainingAmount = paymentMapper.calculateRemainingAmount(projectId);
            return Result.success(remainingAmount);
        } catch (Exception e) {
            return Result.error(500, "计算剩余待回款金额失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> batchCreatePayments(List<Payment> payments) {
        try {
            for (Payment payment : payments) {
                // 设置默认值
                if (payment.getPaymentStatus() == null) {
                    payment.setPaymentStatus("已到账");
                }
                if (payment.getIsPartialPayment() == null) {
                    payment.setIsPartialPayment(0);
                }
                if (payment.getRemainingAmount() == null) {
                    payment.setRemainingAmount(BigDecimal.ZERO);
                }
                
                payment.setCreateTime(LocalDateTime.now());
                payment.setUpdateTime(LocalDateTime.now());
            }
            
            saveBatch(payments);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "批量创建回款记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deletePayment(Long id) {
        try {
            Payment payment = getById(id);
            if (payment == null) {
                return Result.error(404, "回款记录不存在");
            }
            
            boolean result = removeById(id);
            if (result) {
                return Result.success();
            } else {
                return Result.error(500, "删除回款记录失败");
            }
        } catch (Exception e) {
            return Result.error(500, "删除回款记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PaymentDTO> getPaymentById(Long id) {
        try {
            Payment payment = getById(id);
            if (payment == null) {
                return Result.error(404, "回款记录不存在");
            }
            
            // 转换为DTO
            PaymentDTO paymentDTO = new PaymentDTO();
            paymentDTO.setId(payment.getId());
            paymentDTO.setProjectId(payment.getProjectId());
            paymentDTO.setPaymentNo(payment.getPaymentNo());
            paymentDTO.setAmount(payment.getAmount());
            paymentDTO.setPaymentDate(payment.getPaymentDate());
            paymentDTO.setPayerName(payment.getPayerName());
            paymentDTO.setBankName(payment.getBankName());
            paymentDTO.setBankAccount(payment.getBankAccount());
            paymentDTO.setPaymentMethod(payment.getPaymentMethod());
            paymentDTO.setVoucherUrl(payment.getVoucherUrl());
            paymentDTO.setRemark(payment.getRemark());
            paymentDTO.setSettlementType(payment.getSettlementType());
            paymentDTO.setIsPartialPayment(payment.getIsPartialPayment());
            paymentDTO.setRemainingAmount(payment.getRemainingAmount());
            paymentDTO.setPaymentStatus(payment.getPaymentStatus());
            
            return Result.success(paymentDTO);
        } catch (Exception e) {
            return Result.error(500, "查询回款记录失败：" + e.getMessage());
        }
    }
}
